package com.six.exception;

import com.six.util.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletResponse;

/**
 * 统一异常处理
 * @author: hui.zhang
 * @date: 2020/1/29 9:02 PM
 **/

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

	/**
	 * 参数异常验证
	 * @param response
	 * @param e
	 * @return
	 * @throws Exception
	 */
	@ExceptionHandler(value = MethodArgumentNotValidException.class)
	public Object methodArgumentNotValidException(HttpServletResponse response, Exception e) {
		int status = HttpStatus.BAD_REQUEST.value();
		response.setStatus(status);
		MethodArgumentNotValidException ex = (MethodArgumentNotValidException)e;
		return Result.build(status, ex.getBindingResult().getFieldError().getDefaultMessage());
	}

}
